<?php

namespace app\company\service\iot\setting;

use app\common\config\iot_setting_Config\IotSettingConfig;
use app\common\Message;
use app\model\iot_model\IotFunctionRoom;
use app\model\iot_model\IotGrouping;
use app\model\iot_model\IotRoom;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SettingIot
{
    use Message;

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function addGrouping($data): bool
    {
        $typeMode = new IotGrouping();
        $key = ['name','remark','is_show'];
        if(!isset($data['rank_num'])){
            $data['rank_num'] = 0;
        }
        foreach($key as $value){
            if(!check_array_key($value,$data)){
                $this->message = '缺少参数！';
                return false;
            }else{
                switch ($value){
                    case 'name':
                        $where = [
                            ['company_id','=',$data['company_id']],
                            ['name','=',$data['name']],
                        ];
                        $name = IotGrouping::query()->where($where)->find();
                        if(!empty($name)){
                            $this->message = '分组名称不能重复！';
                            return false;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        $insert = [
            'name'=>$data['name'],
            'remark'=>$data['remark'],
            'company_id'=>$data['company_id'],
            'areas_id'=>$data['areas_id'],
            'unit_id'=>$data['unit_id'],
            'user_id'=>$data['uid'],
            'rank_num'=>$data['rank_num'],
            'create_time'=>time(),
            'is_show'=>$data['is_show'],
        ];
        $typeMode->insert($insert);
        $this->result =1;
        $this->message = '操作成功！';
        return true;
    }

    public function isShow($data): bool
    {
        switch ($data['type']){
            case 'grouping':
                $typeMode = new IotGrouping();
                break;
            case 'function_room':
                $typeMode = new IotFunctionRoom();
                break;
            default:
                $this->message = '参数错误！';
                return false;
        }
        $setKey = ['ids','is_show'];
        foreach($setKey as $v){
            if(!check_array_key($v,$data)){
                $this->message = '缺少要设置的参数'.$v;
                return false;
            }
        }
        $where = [
            ['company_id','=',$data['company_id']],
            ['id','in',$data['ids']],
        ];
        $isSelf = $typeMode->where($where)->find();
        if(empty($isSelf)){
            $this->message = '暂无数据！';
            return false;
        }
        $typeMode->where('id','in',$data['ids'])->update(['is_show'=>$data['is_show'],'update_time'=>time()]);
        $this->result = 0;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getGroupingList($data): bool
    {
        $typeMode = new IotGrouping();
        $where[] = [
            ['company_id','=',$data['company_id']],
        ];
        if(isset($data['is_show'])){
            if($data['is_show'] ==0 || $data['is_show'] ==1){
                $where[] = [
                    ['is_show','=',$data['is_show']],
                ];
            }
        }
        $list = $typeMode->where($where)
            ->field('id,name,remark,create_time,is_show,default')
            ->paginate($data['page_size']);
        $data2 = [];
        $iotRoomId = IotRoom::query()->where([
            ['company_id','=',$data['company_id']],
            ['type_id','=',0],
        ])->value('id');
        if ($list->currentPage() == 1 && $iotRoomId){
            $data2[] = [
                'id'=>0,
                'name' => '未分类',
                'remark' => '默认分类不可删除，该分类下无内容时不展示',
                'is_show' => 1,
            ];
            foreach ($list->toArray()['data'] as $item){
                $data2[] = $item;
            }
        }else{
            $data2 = $list->toArray()['data'];
        }
        $return = ['total' => $list->total(), 'page' => $data['page'], 'page_size' => $data['page_size'],'list' => $data2];
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getAllDate($data): bool
    {
        switch ($data['type']){
            case 'grouping':
                $typeMode = new IotGrouping();
                break;
            case 'function_room':
                $typeMode = new IotFunctionRoom();
                break;
            default:
                $this->message = '参数错误！';
                return false;
        }
        $where[] = [
            ['company_id','=',$data['company_id']],
        ];
        if(isset($data['is_show'])){
            if($data['is_show'] ==0 || $data['is_show'] ==1){
                $where[] = [
                    ['is_show','=',$data['is_show']],
                ];
            }
        }
        $list = $typeMode->where($where)->field('id')->select();
        $this->result = arrayDrop($list->toArray());
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function delGrouping($data): bool
    {
        $typeMode = new IotGrouping();
        if(!check_array_key('ids',$data)){
            $this->message = '缺少要删除的参数id';
            return false;
        }
        if ($data['ids'] == 0){
            $this->message = '不能删除默认的数据';
            return false;
        }
        //验证删除之前是否有已创建的数据，如果有提示用户，不能直接删除，先去设备管理处删除
        $roomWhere = [
            ['company_id','=',$data['company_id']],
            ['type_id','in',$data['ids']],
        ];
        $room = IotRoom::query()->where($roomWhere)->field('id,company_id,name_id')->find();
        if(!empty($room)){
//            $this->message = '物联网设备管理处已经使用此功能室分组，如需删除功能室分组请先删除设备管理处的数据！';
//            return false;
            IotRoom::query()->where($roomWhere)->update(['type_id'=>0]);
        }
        $where = [
            ['company_id','=',$data['company_id']],
            ['id','in',$data['ids']],
            ['default','=',1],
        ];
        $isSelf = $typeMode->where($where)->find();
        if(!empty($isSelf)){
            $this->message = '不能删除默认的数据！';
            return false;
        }
        $typeMode->where('id','in',$data['ids'])->update(['is_del'=>1,'del_time'=>time()]);
        $this->result = 0;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function editGrouping($data): bool
    {
        $typeMode = new IotGrouping();
        if(!check_array_key('id',$data)){
            $this->message = '缺少要编辑的参数id';
            return false;
        }
        $where = [
            ['company_id','=',$data['company_id']],
            ['id','=',$data['id']],
        ];
        $isSelf = $typeMode->where($where)->find();
        if(empty($isSelf)){
            $this->message = '暂无数据！';
            return false;
        }
        $key = ['user_id','name','is_show','rank_num','remark'];
        foreach($key as $value){
            if(check_array_key($value,$data)){
                if ($value == 'name') {
                    $wheres = [
                        ['id', '<>', $data['id']],
                        ['name', '=', $data['name']],
                        ['company_id', '=', $data['company_id']],
                    ];
                    $name = IotGrouping::query()->where($wheres)->select();
                    if (count($name) > 0) {
                        $this->message = '分组名称不能重复！';
                        return false;
                    }
                }
                $updateArr[$value] = $data[$value];
            }
        }
        $updateArr['update_time'] = time();
        $typeMode->where('id',$data['id'])->update($updateArr);
        $this->result = 0;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function addFunctionRoom($data): bool
    {
        $typeMode = new IotFunctionRoom();
        $key = IotSettingConfig::getAddFunctionRoomKey();
        if(!isset($data['rank_num'])){
            $data['rank_num'] = 0;
        }
        foreach($key as $value){
            if(!check_array_key($value,$data)){
                $this->message = '缺少参数！'.$value;
                return false;
            }else{
                $message = match ($value) {
                    'name' => '功能室名称不能重复！',
                    'code' => '功能室代号不能重复！',
                    default => '',
                };
                if(!empty($message)){
                    $where['company_id'] = $data['company_id'];
                    $where[$value] = $data[$value];
                    $name = IotFunctionRoom::query()->where($where)->find();
                    if(!empty($name)){
                        $this->message = $message;
                        return false;
                    }
                }
            }
        }
        $insert = [
            'name'=>$data['name'],
            'remark'=>$data['remark'],
            'company_id'=>$data['company_id'],
            'areas_id'=>$data['areas_id'],
            'unit_id'=>$data['unit_id'],
            'create_uid'=>$data['uid'],
            'rank_num'=>$data['rank_num'],
            'img'=>$data['img'],
            'code'=>$data['code'],
            'create_time'=>time(),
            'is_show'=>$data['is_show'],
        ];
        $typeMode->insert($insert);
        $this->result =1;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getFunctionRoomList($data): bool
    {
        $typeMode = new IotFunctionRoom();
        $where[] = [
            ['company_id','=',$data['company_id']],
        ];
        if(isset($data['is_show'])){
            if($data['is_show'] ==0 || $data['is_show'] ==1){
                $where[] = [
                    ['is_show','=',$data['is_show']],
                ];
            }
        }
        $list = $typeMode->where($where)
            ->field('id,name,remark,img,code,create_time,is_show,default')
            ->paginate($data['page_size']);
        $return = ['total' => $list->total(), 'page' => $data['page'], 'page_size' => $data['page_size'],'list' => $list->toArray()['data']];
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function delFunctionRoom($data): bool
    {
        $typeMode = new IotFunctionRoom();
        if(!check_array_key('ids',$data)){
            $this->message = '缺少要删除的参数id';
            return false;
        }
        //验证删除之前是否有已创建的数据，如果有提示用户，不能直接删除，先去设备管理处删除
        $roomWhere = [
            ['company_id','=',$data['company_id']],
            ['name_id','in',$data['ids']],
        ];
        $room = IotRoom::query()->where($roomWhere)->field('id,company_id,name_id')->find();
        if(!empty($room)){
            $this->message = '物联网设备管理处已经使用此功能室，如需删除功能室请先删除设备管理处的数据！';
            return false;
        }
        $where = [
            ['company_id','=',$data['company_id']],
            ['id','in',$data['ids']],
        ];
        $isSelf = $typeMode->where($where)->find();
        if(empty($isSelf)){
            $this->message = '删除的ID参数错误！';
            return false;
        }
        $typeMode->where('id','in',$data['ids'])->update(['is_del'=>1,'del_time'=>time()]);
        $this->result = 0;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function editFunctionRoom($data): bool
    {
        $typeMode = new IotFunctionRoom();
        if(!check_array_key('id',$data)){
            $this->message = '缺少要编辑的参数id';
            return false;
        }
        $where = [
            ['company_id','=',$data['company_id']],
            ['id','=',$data['id']],
        ];
        $isSelf = $typeMode->where($where)->find();
        if(empty($isSelf)){
            $this->message = '暂无数据！';
            return false;
        }
        $key = IotSettingConfig::getAddFunctionRoomKey();
        foreach($key as $value){
            if(check_array_key($value,$data)){
                $message = match ($value) {
                    'name' => '分组名称不能重复！',
                    'code' => '功能室代号不能重复！',
                    default => '',
                };
                if(!empty($message)){
                    $wheres[] = ['id','<>',$data['id']];
                    $wheres[] = [$value,'=',$data[$value]];
                    $wheres[] = ['company_id','=',$data['company_id']];
                    $name = IotFunctionRoom::query()->where($wheres)->find();
                    if(!empty($name)){
                        $this->message = $message;
                        return false;
                    }
                }
                $updateArr[$value] = $data[$value];
            }
        }
        $updateArr['update_time'] = time();
        $typeMode->where('id',$data['id'])->update($updateArr);
        $this->result = 0;
        $this->message = '操作成功！';
        return true;
    }

}